package com.hanson.data_conveying.task;

import com.alibaba.fastjson.JSONObject;
import com.hanson.data_conveying.ConveyingTask;
import com.hanson.entity.TbConveyLog;
import com.hanson.entity.TbSellData;
import com.hanson.repository.ConveyLogRepository;
import com.hanson.repository.SellDataRepository;
import com.hanson.utils.ThreadPoolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description: 温蒂数据传输样式
 * @classname: WendyTask
 * @author: HansonLee
 * @create: 2024/03/26
 **/
@Component
public class WendyTask {
    public final static String SELL_DATA = "XS";
    public final static String STORE_DATA = "MD";
    public final static String STOCK_DATA = "KC";
    public final static String CUSTOMER_FLOW_DATA = "KL";
    public final static String SETTLE_DATA = "JS";
    public final static String CREATOR = "WendyConvey";
    public final static String COMPANY = "Wendy";

    @Autowired
    private SellDataRepository sellDataRepository ;
    @Autowired
    private ConveyLogRepository conveyLogRepository;
    //= SpringContextUtil.getBean("conveyLogRepository");
    @Value("127.0.0.1")
    private String host;
    @Value("${server.port}")
    private String port;
    @Autowired
    private RestTemplate restTemplate ;


    //首次传输
    public void convey(){
        //检查传输情况
        TbConveyLog checkLog = new TbConveyLog()
                .setStringTime(new SimpleDateFormat("yyyyMMdd").format(new Date()))
                .setType(SELL_DATA)
                .setCompany(COMPANY);
        Example<TbConveyLog> conveyLogExample = Example.of(checkLog);
        Optional<TbConveyLog> hasConvey = conveyLogRepository.findOne(conveyLogExample);
        if (hasConvey.isPresent())
            return;
        //销售数据
        ConveyingTask<List<TbSellData>, String> sellDataTask = new ConveyingTask<>();
        sellDataTask.supplier(()-> sellDataRepository.findAll())
                .function((data)->{
                    //split data
                    Objects.requireNonNull(data);
                    int limit = 2;
                    int count = (data.size() > limit) ? (int) Math.ceil(data.size() / limit) : 1;
                    //ready to execute
                    String[] sharding = new String[count + 1];
                    int fromIndex = 0;
                    int toIndex = limit-1;
                    for (int i = 0; i < count; i++) {
                        try {
                            String url = "http://" + host +":" + port + "/convey/sell_data";
                            List<TbSellData> subList;
                            if (count > 1){
                                subList = data.subList(fromIndex, toIndex);
                            }else {
                                subList = data;
                            }
                            fromIndex = toIndex;
                            toIndex = fromIndex + limit -1;
                            if(toIndex > data.size()){
                                toIndex = data.size();
                            }
                            Object json = JSONObject.toJSON(subList);
                            String rs = restTemplate.postForObject(url, json, String.class);
                            //end handle
                            sharding[i] = "conveying sharding data: " + data.get(i);
                            String success = "receive success";
                            sharding[i] = success.equals(rs)?sharding[i] + "\t---->" + rs:sharding[i] + "\tfailed" + rs;
                            //finished
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                            //log exception to database
                        }
                    }
                    String msg = "success pull";
                    sharding[count] = msg;
                    StringBuffer rs = new StringBuffer();
                    for (int i = 0; i < sharding.length; i++) {
                        rs = i == sharding.length-1 ?rs.append(sharding[i]):rs.append(sharding[i] + "\n");
                    }
                    return rs.toString();

                })
                .consumer(rs->{
                    TbConveyLog tbConveyLog = new TbConveyLog();
                    tbConveyLog.setLog(rs).setCompany(COMPANY)
                            .setStatus(1).setType(SELL_DATA)
                            .setCreateTime(new Date())
                            .setStringTime(new SimpleDateFormat("yyyyMMdd").format(new Date()))
                            .setCreateBy(CREATOR);
                    conveyLogRepository.save(tbConveyLog);
                });
        ThreadPoolUtil.getPool().execute(sellDataTask);

        //门店数据

        //库存数据

        //客流数据

        //结算数据

    }
    //数据补传
    public void reConvey(List<String> conveyList){

    }
}
